// 坐标取地址
function getAddressName(lng, lat) {
  var dfd = $.Deferred()
  AMap.service('AMap.Geocoder', function () {
    geocoder = new AMap.Geocoder({
      city: "010"//城市，默认：“全国”
    });
    var lnglatXY = [lng, lat];//关联的坐标
    geocoder.getAddress(lnglatXY, function (status, result) {
      if (status === 'complete' && result.info === 'OK') {
        dfd.resolve(result.regeocode.formattedAddress);
      } else {
        dfd.resolve('未找到有效地址');
      }
    });
  })

 return dfd.promise();
}


(function (window, $, undefined) {
  'use strict';

  var dictData = {
    orderChannel: { //订单来源
      '1': '小程序',
      '2': '管理后台',
      '3': 'iOS',
      '4': '安卓'
    },
    orderType: {  //服务类型
      // '1': '立即接机',
      // '2': '立即接站',
      // '3': '预约接机',
      // '4': '预约接站',
      // '5': '预约送机',
      // '6': '预约送站',
      // '7': '预约用车',
      // '8': '立即用车'
    },
    bookModel: {  //车辆类型
      '1': '舒适型',
      '2': '商务7座',
      '3': '豪华轿车'
    },
    vehiclePurpose:{

    },
    payType: {  //支付类型     paymentType
      '1': '乘客支付',
      '2': '司机代付'
    },
    payChannel: { //支付渠道
      '1': '微信',
      '2': '支付宝',
      '3': '银联',
      '4': '账户扣款',
      '5': '企业代扣',
      '9': '其他'
    },
    orderState: { //订单状态
      '1': '等待接单',
      '2': '预约成功',
      '3': '已派车',
      '4': '司机出发',
      '5': '司机到达出发地',
      '6': '乘客已上车',
      '7': '行程中',
      '8': '行程结束待计算价格',
      '9': '行程结束待付款',
      '10': '标注已付款（用于司机代付）',
      '11': '已支付（确实已付款，来自支付渠道的返回结果）',
      '12': '已评价',
      '13': '已取消',
      '14': '派车失败下单失败',
      '15': '运力不足下单失败',
      '20': '已关闭',
      //字典返回的
      // '1':'等待接单',
      // '2':'预约成功',
      // '3':'已派车',
      // '4':'司机出发',
      // '5':'司机到达出发地',
      // '6':'乘客已上车',
      // '7': '行程中',
      // '8': '行程结束待计算价格',
      // '9': '行程结束待付款',
      // '10': '标注已付款（用于司机代付）',
      // '11': '已支付（确实已付款，来自支付渠道的返回结果）',
      // '12': '已评价',
      // '13': '已取消',
    },
    autoModelId:{

    },
    state:{
      '0': '离线',
      '1': '上线',
      '2': '待命',
      '3': '入栈中',
      '4': '入栈',
      '5': '服务中'
    }
  };

  var cityData = {};

  var orderData = {};

  var driverData = {};

  main(function () {


    //获取操作人并修改
    $("span[data-operator]").text(oUser.account)

    var $tableOrder = $('#table-order');
    util.jqGrid($tableOrder, {
      url:ajaxURL.ORDER+'/order/queryOrderIngList',
      // mtype: 'POST',
      serializeGridData: function (postData) {
        var newData = {
          pageNum:postData.pageNum,
          pageSize:postData.pageSize,
          orderNo:postData.orderNo,
          autoNo:postData.autoNo,
          driverPhone:postData.driverPhone,
          placingUserPhone:postData.placingUserPhone,
          orderState:postData.orderState
        };
        return newData
      },
      // datatype: 'json',
      autowidth: true,
      height: $(window).height() - 350,
      multiselect: true,
      multiboxonly: true,
      shrinkToFit: false,
      colModel: [
        // { name: 'orderNo', key: true, hidden: true },
        // { label: '编号', name: '', width: 50 },
        {
          label: '订单编号（ID）', key: true, name: 'orderNo', width: 150, formatter: function (v, o, r) {
            return '<a href="javascript:;" class="view" data-id="' + r.orderNo + '">' + v + '</a>';
          }
        },
        { label: '创建时间', name: 'createTime', width: 150, formatter: function (v) {
          return util.dateFormat(v);
        } },
        { label: '用车时间', name: 'planDepartTime', width: 150, formatter: function (v) {
          return util.dateFormat(v);
        } },
        { label: '出发城市', name: 'planOrigCityId', width: 50, formatter: function (v) {
          return cityData[v] || '';
        } },
        {
          label: '服务类型', name: 'orderType', width: 80, formatter: function (v) {
          return dictData.orderType[v] || '';
        } },
        {
          label: '用车类型', name: 'bookModel', width: 80, formatter: function (v) {
          return dictData.bookModel[v] || '';
        } },
        { label: '车牌号', name: 'autoNo', width: 100 },
        { label: '下单人', name: 'placingUserPhone', width: 100 },
        { label: '用车人', name: 'passengerPhone', width: 100 },
        { label: '司机ID', name: 'driverId', width: 50 },
        { label: '司机电话', name: 'driverPhone', width: 100 },
        { label: '订单状态', name: 'orderState', width: 150, formatter: function (v) {
          return dictData.orderState[v] || '';
        } },
        { label: '支付类型', name: 'payType', width: 100, formatter: function (v) {
          return dictData.payType[v] || '';
        } },
        { label: '订单来源', name: 'orderChannel', width: 100, formatter: function (v) {
          return dictData.orderChannel[v] || '';
        } },
        {name:'orderState',hidden:true}
      ],
      loadComplete: function (res) {
        orderData = {};
        if (res && res.data) {
          $.each(res.data, function (_, item) {
            orderData[item.orderNo] = item;
          });
        }
      },
      pager: '#pager-order'
    });
    var $tableRedispatch = $('#table-order-redispatch');
    // function getDriver(){
      util.jqGrid($tableRedispatch, {
        url: ajaxURL.ORGANIZATION+'/driver/getDriverList',
        datatype: 'json',
        postData:{

        },
        width: 960,
        height: 300,
        multiselect: true,
        multiboxonly: true,
        // shrinkToFit: false,
        colModel: [
          { name: 'kid', key: true, hidden: true },
          { label: '司机ID', name: 'kid', width: 50 },
          { label: '司机姓名', name: 'name', width: 100 },
          { label: '车牌号', name: 'autoNo', width: 100 },
          { label: '司机电话', name: 'phone', width: 150 },
          { label: '当前车辆定位', name: '_curPosition', width: 200 },
          { label: '据上车地', name: '', width: 100 },
          { label: '司机状态', name: 'state', width: 80 ,formatter: function (v) {
            return dictData.state[v] || ''}
          }
        ],
        loadComplete: function (res) {
          driverData = {};
          if (res && res.data) {
            $.each(res.data, function (_, item) {
              driverData[item.kid] = item;
            });
          }
        },
        pager: '#pager-order-redispatch',
        gridComplete: function() {
          var ids = $tableRedispatch.jqGrid('getDataIDs');
          ids.forEach(function (id, index) {
            var rowData = $tableRedispatch.jqGrid('getRowData', id)
            getAddressName(rowData.lng, rowData.lat).done(function(data) {
              $tableRedispatch.jqGrid('setRowData', id, {
                _curPosition: data
              } )
            })
          });
        }
      });
    // }



    // 字典下拉数据
    util.selectHtml('[name="orderType"]', dictData.orderType, '', '', '请选择');
    util.selectHtml('[name="bookModel"]', dictData.bookModel, '', '', '请选择');
    util.selectHtml('[name="orderChannel"]', dictData.orderChannel, '', '', '请选择');
    util.selectHtml('[name="payType"]', dictData.payType, '', '', '请选择');
    util.selectHtml('[name="payChannel"]', dictData.payChannel, '', '', '请选择');

    //订单状态
    util.getDict('orderState', 'orderState').then(function (data) {
      util.selectHtml('[name="orderState"]', data, 'value', 'name', '请选择');
      $.each(data, function (_, item) {
        dictData.orderState[item.value] = item.name;
      });
    });


    //订单类型
    util.getDict('orderType', 'orderType').then(function (data) {
      util.selectHtml('[name="orderType"]', data, 'value', 'name', '请选择');
      $.each(data, function (_, item) {
        dictData.orderType[item.value] = item.name;
      });
    });



    // 获取城市列表
    util.get(ajaxURL.ORGANIZATION + '/city/getCityList?pageNum=1&pageSize=99999', function (res) {
      util.selectHtml($('[name="cityId"]'), res.data, 'cityId', 'name', '请选择');
      $.each(res.data, function (_, item) {
        cityData[item.cityId] = item.name;
      });
      searchTable();
    });

    function searchTable() {
      var data = util.formData('#form-search');
      util.searchGrid($tableOrder, data);
    }
    $('#search-btn').click(searchTable)

    // 创建时间段
    laydate.render({
      range: '至',
      elem: '#created-time',
      done: function (value, date, endDate) {
        var temp = value.split('至');
        $('#created-time').next().val($.trim(temp[0])).next().val($.trim(temp[1]));
      }
    });

    // 里程时间段
    laydate.render({
      range: '至',
      elem: '#journey-time',
      done: function (value, date, endDate) {
        console.log(value, date, endDate);
        var temp = value.split('至');
        $('#journey-time').next().val($.trim(temp[0])).next().val($.trim(temp[1]));
      }
    });

    laydate.render({
      elem: '#plan_depart_time',
      type: 'datetime'
    });

    var $layerOrderAdd = $('#layer-order-add');
    var $formOrderAdd = $('#form-order-add');
    var $validateOrderAdd = $formOrderAdd.validate({
      rules: {
        model: { required: true },
        passenger_phone: { required: true, isPhone: true },
        plan_depart_time: { required: true },
        order_type: { required: true },
        book_model: { required: true },
        cityId: { required: true },
        initAddress: { required: true },
        plan_dest: { required: true },
        plan_dest_lng: { required: true },
        plan_dest_lat: { required: true }
      },
      messages: {
        model: { required: '请选择用车目的' },
        passenger_phone: { required: '请输入乘车人电话' },
        plan_depart_time: { required: '请输入用车时间' },
        order_type: { required: '请选择服务类型' },
        book_model: { required: '请选择车辆类型' },
        cityId: { required: '请选择城市' },
        initAddress: { required: '请选择上车地点' },
        plan_dest: { required: '请输入详细地址' },
        plan_dest_lng: { required: '请输入经度' },
        plan_dest_lat: { required: '请输入纬度' }
      }
    });

    // 新增操作
    $('#btn-add').click(function () {
      util.resetForm($formOrderAdd);
      $('#initAddress').attr('disabled', 'disabled').val('').html('');
      $btnPickAddress.attr('disabled', 'disabled');

      util.layerOpen2({
        title: '新建订单',
        content: $layerOrderAdd,
        area: ['1000px', ''],
        btn: ['创建订单', '取消'],
        yes: function (index) {
          var data = util.formData($formOrderAdd);

          if ($validateOrderAdd.form()) {
            // 获取预估信息
            getCaculatePrice(data, function (result) {
              // 要提交的保存的数据
              var orderData = {
                placing_user_id: 1,
                placing_user_phone: '13211111111',
                passenger_phone: data.passenger_phone,
                is_self: 1,
                airport_id: data.order_type === '1' ? curOrigin.airportId : '',
                station_id: data.order_type === '2' ? curOrigin.stationId : '',
                order_channel: 2,
                plan_depart_time: util.getTime(data.plan_depart_time),
                plan_orig_city_id: data.cityId,
                plan_orig: curOrigin.name,
                plan_orig_lng: curOrigin.lng,
                plan_orig_lat: curOrigin.lat,
                plan_dest: data.plan_dest,
                plan_dest_city_id: 0,
                plan_dest_lng: data.plan_dest_lng,
                plan_dest_lat: data.plan_dest_lat,
                plan_mileage: result.mileage,
                plan_price: result.totalFee,
                plan_duration: result.time,
                order_type: data.order_type,
                model: data.model,
                // 运价类型
                fare_type: result.calType
              };
              util.post(ajaxURL.ORDER + '/order/createOrder?' + $.param(orderData), function (res) {
                layer.close(index);
                var strMsg = '新增创建成功，订单号： ' + res.data;
                strMsg += '<br><br>自动进入派车流程，操作完成之前本后台系统不能直接进行预览。';

                layer.alert(strMsg, { icon: 1 });
                $tableOrder.trigger('reloadGrid');
              });
            });
          }
        }
      }, '正在创建订单，是否退出？');
    });

    // 选择地址
    var $btnPickAddress = $('#btn-pick-address');
    var $addDestLat = $btnPickAddress.prev();
    var $addDestLng = $addDestLat.prev();
    var $addPlanDest = $addDestLng.prev();
    util.dragMap({
      selector: $btnPickAddress,
      callback: function (data) {
        $addPlanDest.val(data.address);
        $addDestLng.val(data.position.lng);
        $addDestLat.val(data.position.lat);
        $validateOrderAdd.form();
      }
    });

    // 缓存可用地址信息
    var cacheAddress = {};
    // 当前地址列表
    var cachePos = {};
    // 当前选择的地址
    var curOrigin = {};
    // 获取上车地点
    function getInitAddress() {
      $('#initAddress').attr('disabled', 'disabled').val('').html('');
      $btnPickAddress.attr('disabled', 'disabled');
      curOrigin = {};
      $addDestLat.val('');
      $addDestLng.val('');
      $addPlanDest.val('');
      $('#calc-info').empty();
      var data = util.formData($formOrderAdd);
      if (data.cityId !== '' && data.order_type !== '') {
        var key = data.cityId + ',' + data.order_type;

        if (cacheAddress[key]) {
          enableInitAddress(cacheAddress[key]);
          return;
        }

        var url = ajaxURL.ORGANIZATION + (data.order_type === '1' ? '/airport/getAirportTerminalList' : '/station/getStationExitList') + '?cityId=' + data.cityId;
        util.get(url, function (res) {
          if (res.data && res.data.length > 0) {
            cacheAddress[key] = res.data;
            enableInitAddress(res.data);
          } else {
            util.tip.warn('该城市暂未设置' + (data.order_type === '1' ? '航站楼' : '出站口') + '，请重新选择');
          }
        });
      }
    }

    function enableInitAddress(data) {
      cachePos = {};
      util.selectHtml('#initAddress', data, 'kid', 'name', '请选择');
      $('#initAddress').removeAttr('disabled');
      $.each(data, function (_, item) {
        cachePos[item.kid] = item;
      });
    }

    $('#add-cityId, #add-order_type').change(getInitAddress);

    // 切换上车地点
    $('#initAddress').change(function () {
      var val = $(this).val();
      $btnPickAddress.attr('disabled', 'disabled');
      curOrigin = {};
      if (val !== '') {
        $btnPickAddress.removeAttr('disabled');
        curOrigin = cachePos[val];
        $btnPickAddress.data({lng: curOrigin.lng, lat: curOrigin.lat});
      }

    });

    // 记录联动组合的缓存数据
    var cachePrice = {};
    var canGetPrice = false;

    // 下拉框联动
    function checkPrice() {
      canGetPrice = false;
      var data = util.formData($formOrderAdd);
      if (data.order_type !== '' && data.cityId !== '' && data.book_model !== '') {
        hasPrice(data).then(function (ret) {
          canGetPrice = ret;
          if (!ret) {
            util.tip.warn('当前条件下无可用报价规则信息，请重新选择');
          }
        });
      // } else {
      //   console.log('条件不全');
      }
    }

    $('#add-cityId, #add-order_type, #add-book_model').change(checkPrice);

    // 根据条件查询是否有报价基础信息
    function hasPrice(data) {
      var dfd = $.Deferred();
      var condition = {
        pageNum: 1,
        pageSize: 15,
        status: 101,
        type: data.order_type,
        cityId: data.cityId,
        carType: data.book_model
      };

      var key = data.order_type + ',' + data.cityId + ',' + data.book_model;

      if (cachePrice[key] !== undefined) {
        return dfd.resolve(cachePrice[key]);
      }

      util.get(ajaxURL.PRICE + '/caculationrule/getPriceCaculationRuleListByCondition', condition, function (res) {
        var ret = false;
        if (res.data && res.data[0]) {
          ret = res.data[0];
          cachePrice[key] = ret;
        }
        return dfd.resolve(ret);
      });

      return dfd.promise();
    }

    // 根据条件查询预估报价
    var curCalcPriceData = {};
    function getCaculatePrice(data, callback) {
      curCalcPriceData = {};
      $('#calc-info').empty();
      if (canGetPrice) {
        var postData = {
          customerId: data.passenger_phone,
          carType: data.book_model,
          cityId: data.cityId,
          destination: data.plan_dest_lng + ',' + data.plan_dest_lat,
          origin: curOrigin.lng + ',' + curOrigin.lat,
          orderStartTime: util.getTime(data.plan_depart_time),
        };
        util.post(ajaxURL.PRICE + '/caculationprice/caculatePrice', postData, function (res) {
          curCalcPriceData = res.data;
          $('#calc-info').html(function () {
            var ret = '';
            ret += '预估价格：' + (+(curCalcPriceData.totalFee / 100).toFixed(2) + '元');
            ret += '&emsp;预估里程：' + (+(curCalcPriceData.mileage / 1000).toFixed(2) + '公里');

            return ret;
          });
          if (res.data && $.isFunction(callback)) {
            callback(res.data);
          }
        });
      } else {
        util.tip.warn('无可用报价信息');
      }
    }

    $('#btn-calc-price').click(function () {
      var data = util.formData($formOrderAdd);
      if ($validateOrderAdd.form()) {
        getCaculatePrice(data, function (data) {
        });
      }
    });

    // 查看订单
    var $formOrderView = $('#form-order-view');
    $tableOrder.on('click', '.view', function () {
      var $this = $(this);
      var id = $this.data('id');
      // 根据 id 请求数据
      var data = $.extend(true,{},orderData[id]);

      util.resetForm($formOrderView);

      data.bookModel = data.model;

      $formOrderView.find('[data-createTime]').text(util.dateFormat(data.createTime) || '');
      $formOrderView.find('[data-orderNo]').text(id);

      //时间处理
      data.paiedTime = util.dateFormat(data.paiedTime);
      data.destTime = util.dateFormat(data.destTime);
      data.depTime = util.dateFormat(data.depTime);

      //价格 里程格式处理
      data.planPrice = util.price(data.planPrice);
      data.factPrice = util.price(data.factPrice);
      // data.startMile = util.toKilometer(data.startMile);
      // data.endMile = util.toKilometer(data.endMile);

      util.fillForm($formOrderView, data);

      util.layerOpen({
        title: false,
        content: $('#layer-order-view'),
        area: ['1000px', '']
      });
    });

    // 改派
    $('#btn-redispatch').click(util.oneCheck($tableOrder, function (id) {

      // if(rowData.orderState){
      //   util.tip.warn('此订单无法改派')
      // }
      $tableRedispatch.jqGrid('clearGridData');

      var $layerOrderRedispatch=$('#layer-order-redispatch');

      var $data = $.extend(true,{},orderData[id]);
      $layerOrderRedispatch.find(':input').removeAttr('disabled');

      //订单ID
      $layerOrderRedispatch.find('[data-clientId]').text(id);

      //城市
      if($data.planOrigCityId===20){
        $layerOrderRedispatch.find('[data-city]').text('武汉');  //城市词典，注：后面应更改如果后台没有字段修改默认
      }else{
        $layerOrderRedispatch.find('[data-city]').text(cityData[$data.planOrigCityId]);
      }

      //服务类型
      $layerOrderRedispatch.find('[data-serveType]').text(dictData.orderType[$data.orderType])
      //车辆类型
      $layerOrderRedispatch.find('[data-carType]').text(dictData.bookModel[$data.bookModel])


      $layerOrderRedispatch.find("select option[value='"+$data.planOrigCityId+"']").attr("selected","selected").parent().attr('disabled','disabled');
      $layerOrderRedispatch.find("select option[value='"+$data.bookModel+"']").attr("selected","selected").parent().attr('disabled','disabled');


      util.layerOpen({
        // title: '改派订单',
        title: false,
        content: $('#layer-order-redispatch')
      });

      util.tip.warn('请先选择改派司机类型进行搜索！')
    }));

    //创建表格改派司机
    // getDriver();


    //根据司机状态搜索查询司机列表
    $('#driver-search').click(function(){
      var searchData=util.formData($('#layer-order-redispatch .d-content .form-row'));
      var sendState = "";
      if($("input[type='checkbox']").is(':checked')===false){
        util.tip.warn('请选择要改派的司机状态！');
        return;
      }else{
        for(var i=0;i<searchData.state.length;i++){
          sendState += searchData.state[i]+','
        }
      }
      sendState = sendState.substring(0,sendState.length - 1)
      var newPostData = {
        cityId:searchData.cityId,
        autoTypeId:searchData.bookModel,
        stateIn:sendState
      };

      //清空表格数据
      $tableRedispatch.jqGrid('clearGridData');
      $tableRedispatch.jqGrid('setGridParam',{  // 重新加载数据
        url: ajaxURL.ORGANIZATION+'/driver/getDriverList',
        datatype:'json',
        postData:newPostData
      }).trigger("reloadGrid");


    })

    //确认改派
    $('.submit').click(util.oneCheck($tableRedispatch,function(id){
      var data = driverData[id];
      var id = Number(id);
      var orderNo = $('#layer-order-redispatch').find('[data-clientId]').text();
      var postData = {
        order_no:orderNo,
        driver_id:id
      }
      layer.confirm('确定将此订单改派给选中司机？', {//
        btn: ['确定', '再想一想']   //'http://192.168.1.110:16102'
      }, function () {
        util.ajax( ajaxURL.SCHEDULE+ '/v1/schedule/record/changeDriver', JSON.stringify(postData), 'POST', util.resCallback(function (res) {
          layer.closeAll();
          util.tip.success('改派成功');
          $tableOrder.trigger('reloadGrid');
        }));
      });
    }))

    // 取消订单
    $('#btn-cancel').click(util.oneCheck($tableOrder, function (id) {
      layer.confirm('确定取消该订单？', {
        btn: ['确定', '再想一想']
      }, function () {
        util.tip.warn('取消操作...');
      });
    }));

    // 导出
    $('#btn-export').click(function () {
      util.tip.warn('导出操作...');
    });

    $('#order-save').click(function () {
      var _v = $validate.form();
      console.log(_v);
    });

  });




})(window, jQuery);
